$(function() {
    var bdbDomainTplSet = {
        /* 页面状态 */
        pageState: {
            tempId: 0,
            noData: 'def' // search: 没有匹配的结果; def: 暂无记录.
        },

        /* 添加 */
        addEvent: function() {
            var _this = this,
                formVerify;

            // 表单验证.
            formVerify = $('#bdb-domain-tpl-record-add-form').validate({
                // onkeyup: false,
                errorElement: "div",
                errorPlacement: function(error, element) {
                    error.addClass("help-block");
                    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
                        error.appendTo(element.parents(".bdb-vc"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(form, e) {
                    e.preventDefault();
                    _this.addSave(form);
                }
            });

            _this.recordVerifyFocusout();
            _this.recordTypeChange();

            // 添加-取消.
            $('#bdb-domain-tpl-record-add-form').off('click').on('click', '#bdb-domain-tpl-record-add-cancel', function(e) {
                bdbMain.mLRManag({mask: false});
                $('#bdb-domain-tpl-record-add-form').hide();
            });

            // 点击添加响应事件.
            $('#bdb-domain-tpl-record-add').off('click').on('click', function(){
                _this.addDefDataProc(formVerify);
            });
        },
        recordVerifyFocusout: function() {
            $('#bdb-domain-tpl-record-add-form, .bdb-list').off('focusout').on('focusout', 'input', function() {
                var msgEle = $(this).parents(".form-group"),
                    _this = $(this);

                if (msgEle.find(".js-bdb-srcTplType").val() == 'A') {
                    if (_this.val() != '') {
                        if (_this.attr("name").indexOf('master') > -1) {
                            _this.rules("add", {
                                required: true,
                                srcTplMasterProc: true,
                                messages: {
                                    required: '请输入ip',
                                    srcTplMasterProc: "ip格式错误"
                                }
                            });
                        } else {
                            _this.rules("add", {
                                required: true,
                                srcTplSlaveProc: true,
                                srcTplMSCompareProc: true,
                                srcTplMRequiredProc: true,
                                messages: {
                                    required: '请输入ip',
                                    srcTplSlaveProc: "ip格式错误",
                                    srcTplMSCompareProc: "主、备ip不能相同",
                                    srcTplMRequiredProc: "主ip为必填项"
                                }
                            });
                        }
                    } else {
                        _this.rules("remove");
                    }
                } else {
                    if (_this.val() != '') {
                        _this.rules("add", {
                            required: true,
                            srcTplMasterProc: true,
                            messages: {
                                required: '请输入CNAME',
                                srcTplMasterProc: "请输入正确的CNAME"
                            }
                        });
                    } else {
                        _this.rules("remove");
                    }
                }
            });
        },
        recordTypeChange: function() {
            $('#bdb-domain-tpl-record-add-form, .bdb-list').off('change').on('change', '.js-bdb-srcTplType', function() {
                var _this = $(this),
                    msgEle = _this.parents('.form-group'),
                    master = msgEle.find('.js-bdb-srcTplMaster'),
                    slave = msgEle.find('.js-bdb-srcTplSlave');

                master.val('');
                master.rules('remove');
                if (_this.val() == 'A') {
                    if (master.hasClass('bdb-record-master')) {
                        master.attr({'placeholder': bdbMain.attr.placeholder.ip});
                        master.rules('add', {
                            required: true,
                            srcTplMasterProc: true,
                            messages: {
                                required: '请输入ip',
                                srcTplMasterProc: 'ip格式错误'
                            }
                        });
                    }

                    slave.removeClass('bdb-v-hide').addClass('bdb-v-show');
                } else {
                    if (master.hasClass('bdb-record-master')) {
                        master.attr({'placeholder': bdbMain.attr.placeholder.cname});
                        master.rules('add', {
                            required: true,
                            srcTplMasterProc: true,
                            messages: {
                                required: '请输入CNAME',
                                srcTplMasterProc: '请输入正确的CNAME'
                            }
                        });
                    }

                    slave.removeClass('bdb-v-show').addClass('bdb-v-hide');
                }

                slave.val('');
                slave.rules('remove');
                master.next().remove();
                slave.next().remove();
                msgEle.find('.has-error').removeClass('has-error');
            });
        },
        addDefDataProcTpl: function(data) {
            var tpl = bdbMain.attr.selDefOptionS2;

            $.each(data.lineList, function(i, n) {
                tpl += '<option value="' + i + '">' + n + '</option>';
            });

            return tpl;
        },
        addDefDataProc: function(formVerify) {
            var _this = this;
            bdbMain.mLRManag({mask: true, loading: true});
            $.post('/CustomerDomainTemplate/domainTemplateInit', function(response) {
                if (response.code == 0) {
                    var linesHtml = '',
                        recordAddEle = $("#bdb-domain-tpl-record-add-form");

                    recordAddEle[0].reset();
                    formVerify.resetForm();
                    linesHtml = _this.addDefDataProcTpl(response.data);
                    recordAddEle.find('#lineId').html(linesHtml);
                    recordAddEle.find('#bdb-record-master').attr('placeholder', bdbMain.attr.placeholder.ip);
                    bdbMain.mLSleep({loading: false}, function() {
                        $('#bdb-domain-tpl-record-add-form').find('.js-bdb-srcTplType').val('A').change();
                        $('#bdb-domain-tpl-record-add-form').find('.js-bdb-srcTplSlave').removeClass('bdb-v-hide').addClass('bdb-v-show').rules('remove');
                        recordAddEle.fadeIn();
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        addSave: function(form) {
            var _this = this,
                form = $(form),
                params = form.serialize() + '&templateId=' + _this.pageState.tempId;

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
            $.post('/CustomerDomainTemplate/addTemplateRecord', params, function(response) {
                if (response.code == 0) {
                    $('#bdb-domain-tpl-record-add-cancel').click();
                    bdbMain.mLRManag({maskDown: 99, mask: false, loading: false, alert: {type: 1, msg: '添加成功.'}});
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },

        /* 列表 */
        listEvent: function() {
            var _this = this;

            $('.bdb-list').off('click.listEvent').on('click.listEvent', function(e) {
                var ele = $(e.target),
                    id = ele.parents('.bdb-list-row').attr('data-record-id');

                if (ele.hasClass('js-bdb-domain-tpl-record-del')) { // 删除.
                    _this.listDel(id);
                } else if (ele.hasClass('js-bdb-domain-tpl-record-set')) { //设置.
                    _this.listRecordSet(id, ele);
                } else if (ele.hasClass('js-bdb-domain-tpl-record-onoff')) { // 禁用、启用.
                    var state = ele.parents('.bdb-list-row').attr('data-record-state');
                    _this.listRecordOnoff(id, state);
                } else if (ele.attr('id') == 'bdb-domain-tpl-record-edit-cancel') { // 编辑-取消
                    ele.parents('#bdb-domain-tpl-record-edit-form').remove();
                    bdbMain.mLRManag({mask: false});
                }
            });
        },
        listDel: function(id) {
            var _this = this;

            bdbMain.confirm({
                textInfo: {
                    content: '确定要删除这条记录？',
                    btn: {}
                },
                // note: true,
                params: {
                    url: '/CustomerDomainTemplate/deleteTemplateRecord',
                    data: {
                        id: id
                    }
                },
                callback: function(ele, params) {
                    _this.listDelCallbackProc(ele, params);
                }
            });
        },
        listDelCallbackProc: function(ele, params) {
            var _this = this;
            ele.hide();

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, loading: true});
            $.post(params.url, {
                templateRecordId: params.data.id
            }, function(response) {
                if (response.code == 0) {
                    bdbMain.mLRManag({mask: false, loading: false, alert: {type: 1, msg: '删除成功'}});
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },
        listRecordOnoff: function(id, state) {
            var _this = this,
                stateText = '',
                onOff = '';

            if (state == 1) {
                stateText = '暂停';
                onOff = 'disable';
            } else {
                stateText = '启用';
                onOff = 'enable';
            }

            bdbMain.confirm({
                textInfo: {
                    content: '确定要' + stateText + '这条记录？',
                    btn: {}
                },
                // note: true,
                params: {
                    url: '/CustomerDomainTemplate/switchTemplateRecord',
                    data: {
                        id: id,
                        state: onOff
                    }
                },
                callback: function(ele, params) {
                    _this.listRecordOnoffCallbackProc(ele, params);
                }
            });
        },
        listRecordOnoffCallbackProc: function(ele, params) {
            var _this = this;
                ele.hide();

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, loading: true});
            $.post(params.url, {
                templateRecordId: params.data.id,
                action: params.data.state
            }, function(response) {
                if (response.code == 0) {
                    var stateText = '';
                    if (params.data.state == 'enable') {
                        stateText = '启用成功';
                    } else {
                        stateText = '暂停成功'
                    }

                    bdbMain.mLRManag({mask: false, loading: false, alert: {type: 1, msg: stateText}});
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },
        listRecordSetProcTpl: function(data, recordInfo) {
            var tpl = '',
                list = bdbMain.attr.selDefOptionS2,
                lineIdSelOpt = '',
                bakCls = '';

            $.each(data.lineList, function(i, n) {
                if (recordInfo.record_line_id == i) {
                    lineIdSelOpt = ' selected';
                } else {
                    lineIdSelOpt = '';
                }

                list += '<option value="' + i + '"' + lineIdSelOpt  + '>' + n + '</option>';
            });

            var masterInput = 'data-rule-required="true" data-msg-required="请输入ip" \
                               data-rule-srctplmasterproc="true" data-msg-srctplmasterproc="ip格式错误" \
                               placeholder="' + bdbMain.attr.placeholder.ip + '" '
            if (recordInfo.record_type == 'CNAME') {
                bakCls = ' bdb-v-hide';
                masterInput = 'data-rule-required="true" data-msg-required="请输入CNAME" \
                               data-rule-srcTplMasterProc="true" data-msg-srcTplMasterProc="请输入正确的CNAME" \
                               placeholder="' + bdbMain.attr.placeholder.cname + '" ';
            }

            tpl += '<form class="bdb-hide" id="bdb-domain-tpl-record-edit-form">\
                        <input type="hidden" name="templateRecordId" value="' + recordInfo.template_record_id + '">\
                        <div class="form-group bdb-clearfix">\
                            <div class="bdb-mx-w-col1 bdb-f-l">&nbsp;</div>\
                            <div class="bdb-mx-w-col2 bdb-f-l">\
                                <div class="bdb-form-select-wrapper bdb-p-r">\
                                    <div class="top-arrow"></div>\
                                    <select class="bdb-form-select" name="lineId" \
                                        data-rule-required="true" data-msg-required="请选择线路">' + list  + '</select>\
                                    <div class="bottom-arrow"></div>\
                                </div>\
                            </div>\
                            <div class="bdb-mx-w-col3 bdb-f-l">\
                                <div class="bdb-form-select-wrapper bdb-p-r">\
                                    <div class="top-arrow"></div>\
                                    <select class="bdb-form-select js-bdb-srcTplType" name="type">\
                                        <option value="A" ' + (recordInfo.record_type == 'A' ? 'selected' : '') + '>A</option>\
                                        <option value="CNAME"  ' + (recordInfo.record_type == 'CNAME' ? 'selected' : '') + '>CNAME</option>\
                                    </select>\
                                    <div class="bottom-arrow"></div>\
                                </div>\
                            </div>\
                            <div class="bdb-mx-w-col4 bdb-f-l">\
                                <input class="bdb-record-master js-bdb-srcTplMaster" name="master" type="text" autocomplete="off" \
                                    value="' + recordInfo.master_record + '" ' + masterInput + '>\
                            </div>\
                            <div class="bdb-mx-w-col5 bdb-f-l">\
                                <input class="bdb-record-bak ' + bakCls + ' js-bdb-srcTplSlave" name="bak" type="text" autocomplete="off" value="' + recordInfo.bak_record + '">\
                            </div>\
                            <div class="bdb-mx-w-col6 bdb-f-l">\
                                <button class="bdb-btn bdb-btn-444858-s1" type="submit">确定</button>\
                                <button class="bdb-btn bdb-btn-444858-s1" id="bdb-domain-tpl-record-edit-cancel" type="button">取消</button>\
                            </div>\
                        </div>\
                    </form>';

            return tpl;
        },
        listRecordSetProc: function(id, data, ele) {
            var _this = this;

            $.post('/CustomerDomainTemplate/templateRecordInfo', {
                templateRecordId: id
            }, function(response) {
                $('#bdb-domain-tpl-record-edit-form').remove();
                if (response.code == 0) {
                    var editHtml = '';
                    editHtml = _this.listRecordSetProcTpl(data, response.data.recordInfo);

                    bdbMain.mLSleep({loading: false}, function() {
                        ele.parents('.bdb-list-row').after(editHtml);
                        $('#bdb-domain-tpl-record-edit-form').fadeIn();
                        _this.listRecordSetVerify();
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        listRecordSet: function(id, ele) {
            var _this = this;
            bdbMain.mLRManag({mask: true, loading: true});
            $.post('/CustomerDomainTemplate/domainTemplateInit', function(response) {
                if (response.code == 0) {
                    _this.listRecordSetProc(id, response.data, ele);
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        listRecordSetVerify: function() {
            var _this = this,
                formVerify;

            // 表单验证.
            formVerify = $('#bdb-domain-tpl-record-edit-form').validate({
                // onkeyup: false,
                errorElement: "div",
                errorPlacement: function(error, element) {
                    error.addClass("help-block");
                    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
                        error.appendTo(element.parents(".bdb-vc"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(form, e) {
                    e.preventDefault();
                    _this.listRecordSave(form);
                }
            });
        },
        listRecordSave: function(form) {
            var _this = this,
                form = $(form);

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
            $.post('/CustomerDomainTemplate/editTemplateRecord', form.serialize(), function(response){
                if (response.code == 0) {
                    $('#bdb-domain-tpl-record-edit-cancel').click();
                    bdbMain.mLRManag({maskDown: 99, mask: false, loading: false, alert: {type: 1, msg: '设置成功.'}});
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },
        listProc: function(data) {
            var tpl = '',
                stateImg = '',
                stateText = '',
                bakRecord = '',
                opeartionHtml = '';


            $.each(data.recordList, function(i, n) {
                if (n.status == 0) {
                    stateImg = 'point-red.svg';
                    stateText = '启用';
                } else {
                    stateImg = 'point-green.svg';
                    stateText = '暂停';
                }

                if (n.record_type == 'A') {
                    bakRecord = n.bak_record ? n.bak_record : '-';
                } else {
                    bakRecord = '-';
                }

                if (n.record_line_name == '默认') {
                    opeartionHtml = '<div class="bdb-option-btn bdb-opeartion-set bdb-p-r bdb-mgn-t-10">\
                                        <a class="js-bdb-domain-tpl-record-set" href="javascript:void(0);">设置</a>\
                                     </div>';
                } else {
                    opeartionHtml = '<div class="bdb-option-btn bdb-p-r bdb-mgn-t-10">\
                                        <a class="js-bdb-domain-tpl-record-onoff" href="javascript:void(0);" data-type="' + n.status + '">' + stateText + '</a>\
                                        <div class="v-line-ffa007"></div>\
                                        <a class="bdb-mgn-l--1 js-bdb-domain-tpl-record-set" href="javascript:void(0);">设置</a>\
                                        <div class="v-line-ffa007"></div>\
                                        <a class="bdb-f-c-c8baac bdb-mgn-l--1 js-bdb-domain-tpl-record-del" href="javascript:void(0);">删除</a>\
                                     </div>';
                }

                tpl += '<div class="bdb-list-row row" data-record-id="' + n.template_record_id + '" data-record-state="' + n.status + '">\
                            <div class="bdb-mx-w-col1"><img src="/static/imgs/global/' + stateImg + '"></div>\
                            <div class="bdb-mx-w-col2">' + n.record_line_name + '</div>\
                            <div class="bdb-mx-w-col3">' + n.record_type + '</div>\
                            <div class="bdb-mx-w-col4 bdb-ellipsis">' + n.master_record + '</div>\
                            <div class="bdb-mx-w-col5">' + bakRecord + '</div>\
                            <div class="bdb-mx-w-col6">' + opeartionHtml + '</div>\
                        </div>';
            });

            return tpl;
        },
        list: function() {
            var _this = this,
                urlParams = bdbMain.getUrlParams();

            bdbMain.mLRManag({mask: true, loading: true});
            _this.pageState.tempId = urlParams['id'];

            // 获取列表.
            $.post('CustomerDomainTemplate/domainTemplateDetail', {
                templateId: urlParams['id']
            }, function(response) {
                var totalRowCnt = 0,
                    listHtml = '';

                if (response.code == 0) {
                    totalRowCnt = response.data.recordList.length;
                    listHtml = _this.listProc(response.data);
                    _this.listNull(totalRowCnt);
                    $('.bdb-list').html(listHtml);
                    bdbMain.mLSleep({mask: false, loading: false});
                    $('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCnt));
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            });
        },
        listNull: function(totalRowCnt) {
            var noResult = $('.bdb-no-result');
            if (totalRowCnt <= 0) {
                noResult.show();
            } else {
                noResult.hide();
            }
        },

        /* 屏幕高度适应 */
        contentSizeResize: function () {
            $(window).resize(function() {
                $('.bdb-list').bdbScreenH(1);
            });
        },

        /* 初始化 */
        init: function() {
            var _this = this;

            _this.addEvent();
            _this.list();
            _this.listEvent();
			_this.contentSizeResize(); // 内容区域屏幕适应.

            $('.bdb-list').bdbScreenH(1); // 右侧列表区域自适应.
        }
    };

    bdbDomainTplSet.init();
});
